#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称: user_api.py
完整存储路径: backend/api/user_api.py
功能说明:
    定义用户管理相关的 API 接口，包括创建、编辑、删除、查询用户账户等功能。
    提供用户登录功能，通过JWT令牌实现用户会话管理。
    
使用说明:
    通过 Flask 蓝图实现，暴露给前端用户管理页面进行交互。支持RESTful API，返回 JSON 格式数据。
"""
from flask import Blueprint, request, jsonify, current_app, g
from flask_jwt_extended import jwt_required, get_jwt_identity, create_access_token
from functools import wraps
from datetime import datetime, timedelta
from backend.models.user import User
from backend.models.system_log import SystemLog
from backend.infrastructure.database import db
from backend.infrastructure.database import db as global_db
from backend.models.role import Role
from backend.services.user_role_service import set_user_roles
from backend.services.unified_log_service import log_service
from backend.decorators.auth_decorators import (
    admin_required, require_permissions, require_self_or_admin
)


user_api = Blueprint('user_api', __name__)

# 保留原有的admin_required装饰器（兼容性）
def admin_required_legacy(fn):
    from functools import wraps
    from flask_jwt_extended import get_jwt
    @wraps(fn)
    def wrapper(*args, **kwargs):
        claims = get_jwt()
        roles = claims.get('roles', [])
        if 'admin' not in roles:
            return jsonify({'success': False, 'message': '仅管理员可操作'}), 403
        return fn(*args, **kwargs)
    return wrapper

# 获取单个用户信息（用于编辑）
@user_api.route('/users/<int:user_id>', methods=['GET'])
@jwt_required()
@require_permissions('user:read')
@require_self_or_admin('user_id')
def get_user(user_id):
    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify({"success": False, "message": "用户不存在", "data": None}), 404
        return jsonify({"success": True, "message": "获取用户信息成功", "data": user.to_dict()}), 200
    except Exception as e:
        return jsonify({"success": False, "message": f"获取用户信息失败: {str(e)}", "data": None}), 500

# 获取系统日志
@user_api.route('/system-logs', methods=['GET'])
@jwt_required()
@admin_required
def get_system_logs():
    try:
        logs = SystemLog.query.order_by(SystemLog.created_at.desc()).limit(100).all()
        logs_list = [log.to_dict() for log in logs]
        return jsonify({"success": True, "message": "获取系统日志成功", "data": logs_list}), 200
    except Exception as e:
        return jsonify({"success": False, "message": f"获取系统日志失败: {str(e)}", "data": None}), 500

# 创建用户
@user_api.route('/users/create', methods=['POST'])
@jwt_required()
@require_permissions('user:create')
def create_user():
    try:
        data = request.get_json()
        print("收到创建用户请求:", data)

        # 验证必填字段
        if not all([data.get('username'), data.get('password'), data.get('roles')]):
            return jsonify({"success": False, "message": "用户名、密码和角色均为必填项", "data": None}), 400

        # 检查用户名是否存在
        if User.query.filter_by(username=data['username']).first():
            return jsonify({"success": False, "message": "用户名已存在", "data": None}), 400

        # 创建用户（使用User模型的password setter自动加密）
        user = User(
            username=data['username'],
            status='active'
        )
        user.password = data['password']
        db.session.add(user)
        db.session.commit()
        
        # 设置多角色
        role_names = data.get('roles', [])
        role_ids = [r.id for r in Role.query.filter(Role.name.in_(role_names)).all()]
        set_user_roles(user.id, role_ids)
        
        print(f"用户创建成功: {user.username} (ID: {user.id})")
        
        # 记录系统管理操作日志
        current_user_id = get_jwt_identity()
        ip_address = request.remote_addr
        # 获取当前用户信息
        try:
            if current_user_id:
                current_user = User.query.get(int(current_user_id))
                operator = current_user.username if current_user else '未知用户'
            else:
                operator = '系统'
        except (ValueError, TypeError):
            operator = '未知用户'
        
        # 记录系统管理操作日志
        log = SystemLog.log_create(
            record=user,
            operator=operator,
            ip_address=ip_address
        )
        if log:
            db.session.add(log)
            db.session.commit()
        
        return jsonify({
            "success": True,
            "message": "用户创建成功",
            "data": {"user_id": user.id}
        }), 201

    except Exception as e:
        db.session.rollback()
        print("用户创建失败:", str(e))
        return jsonify({
            "success": False,
            "message": f"用户创建失败: {str(e)}",
            "data": None
        }), 500

# 编辑用户
@user_api.route('/users/edit/<int:user_id>', methods=['PUT'])
@jwt_required()
@require_permissions('user:edit')
def edit_user(user_id):
    try:
        data = request.get_json()
        user = User.query.get_or_404(user_id)
        old_data = user.to_dict()

        user.username = data.get('username', user.username)
        # 多角色支持
        if 'roles' in data:
            role_names = data.get('roles', [])
            role_ids = [r.id for r in Role.query.filter(Role.name.in_(role_names)).all()]
            set_user_roles(user.id, role_ids)
        user.status = data.get('status', user.status)
        # 可选字段
        user.real_name = data.get('real_name', user.real_name)
        user.mobile = data.get('mobile', user.mobile)
        user.email = data.get('email', user.email)
        user.gender = data.get('gender', user.gender)
        user.department = data.get('department', user.department)
        user.position = data.get('position', user.position)
        user.remark = data.get('remark', user.remark)

        db.session.commit()
        
        # 记录系统管理操作日志
        current_user_id = get_jwt_identity()
        ip_address = request.remote_addr
        # 获取当前用户信息
        try:
            if current_user_id:
                current_user = User.query.get(int(current_user_id))
                operator = current_user.username if current_user else '未知用户'
            else:
                operator = '系统'
        except (ValueError, TypeError):
            operator = '未知用户'
        
        # 记录系统管理操作日志
        log = SystemLog.log_update(
            record=user,
            old_data=old_data,
            operator=operator,
            ip_address=ip_address
        )
        if log:
            db.session.add(log)
            db.session.commit()
        
        return jsonify({"success": True, "message": "用户信息更新成功", "data": user.to_dict()}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({"success": False, "message": f"用户信息更新失败: {str(e)}", "data": None}), 500

# 删除用户
@user_api.route('/users/delete/<int:user_id>', methods=['DELETE'])
@jwt_required()
@require_permissions('user:delete')
def delete_user(user_id):
    try:
        user = User.query.get_or_404(user_id)
        db.session.delete(user)
        db.session.commit()
        print(f"已删除用户 - ID:{user_id}")
        
        # 记录系统管理操作日志
        current_user_id = get_jwt_identity()
        ip_address = request.remote_addr
        # 获取当前用户信息
        try:
            if current_user_id:
                current_user = User.query.get(int(current_user_id))
                operator = current_user.username if current_user else '未知用户'
            else:
                operator = '系统'
        except (ValueError, TypeError):
            operator = '未知用户'
        
        # 记录系统管理操作日志
        log = SystemLog.log_delete(
            record=user,
            operator=operator,
            ip_address=ip_address
        )
        if log:
            db.session.add(log)
            db.session.commit()
        
        return jsonify({"success": True, "message": "用户删除成功", "data": None}), 200
    except Exception as e:
        db.session.rollback()
        print("删除错误:", str(e))
        return jsonify({"success": False, "message": f"用户删除失败: {str(e)}", "data": None}), 500

# 查询用户列表
@user_api.route('/users', methods=['GET'])
@jwt_required()
@require_permissions('user:read')
def get_users():
    try:
        users = User.query.all()
        users_list = [user.to_dict() for user in users]
        return jsonify({"success": True, "message": "获取用户列表成功", "data": users_list}), 200
    except Exception as e:
        return jsonify({"success": False, "message": f"获取用户列表失败: {str(e)}", "data": None}), 500

# 获取当前用户信息
@user_api.route('/users/me', methods=['GET'])
@user_api.route('/users/current', methods=['GET'])  # 添加别名路由
@jwt_required()
def get_current_user():
    try:
        current_user_id = get_jwt_identity()
        if not current_user_id:
            return jsonify({"success": False, "message": "用户未登录", "data": None}), 401
        
        user = User.query.get(current_user_id)
        if not user:
            return jsonify({"success": False, "message": "用户不存在", "data": None}), 404
        
        return jsonify({"success": True, "message": "获取当前用户信息成功", "data": user.to_dict()}), 200
    except Exception as e:
        return jsonify({"success": False, "message": f"获取当前用户信息失败: {str(e)}", "data": None}), 500

# 获取当前用户权限列表
@user_api.route('/users/current/permissions', methods=['GET'])
@jwt_required()
def get_current_user_permissions():
    """获取当前用户的权限列表"""
    try:
        current_user_id = get_jwt_identity()
        if not current_user_id:
            return jsonify({"success": False, "message": "用户未登录", "data": []}), 401
        
        user = User.query.get(current_user_id)
        if not user:
            return jsonify({"success": False, "message": "用户不存在", "data": []}), 404
        
        # 获取用户所有权限
        user_permissions = []
        for role in user.roles:
            for permission in role.permissions:
                if permission.code not in user_permissions:
                    user_permissions.append(permission.code)
        
        return jsonify({
            "success": True, 
            "message": "获取用户权限成功", 
            "data": user_permissions
        }), 200
        
    except Exception as e:
        return jsonify({
            "success": False, 
            "message": f"获取用户权限失败: {str(e)}", 
            "data": []
        }), 500

# 更新当前用户信息
@user_api.route('/users/me', methods=['PUT'])
@jwt_required()
def update_current_user():
    try:
        current_user_id = get_jwt_identity()
        if not current_user_id:
            return jsonify({"success": False, "message": "用户未登录", "data": None}), 401
        
        user = User.query.get(current_user_id)
        if not user:
            return jsonify({"success": False, "message": "用户不存在", "data": None}), 404
        
        data = request.get_json()
        if not data:
            return jsonify({"success": False, "message": "请求数据为空", "data": None}), 400
        
        # 更新用户信息（不允许修改用户名和密码）
        updated_fields = []
        if 'real_name' in data:
            user.real_name = data['real_name']
            updated_fields.append('real_name')
        if 'mobile' in data:
            user.mobile = data['mobile']
            updated_fields.append('mobile')
        if 'email' in data:
            user.email = data['email']
            updated_fields.append('email')
        if 'gender' in data:
            user.gender = data['gender']
            updated_fields.append('gender')
        if 'department' in data:
            user.department = data['department']
            updated_fields.append('department')
        if 'position' in data:
            user.position = data['position']
            updated_fields.append('position')
        if 'remark' in data:
            user.remark = data['remark']
            updated_fields.append('remark')
        
        # 如果没有更新任何字段，直接返回成功
        if not updated_fields:
            return jsonify({"success": True, "message": "没有需要更新的信息", "data": user.to_dict()}), 200
        
        # 提交数据库更改
        try:
            db.session.commit()
        except Exception as db_error:
            db.session.rollback()
            return jsonify({"success": False, "message": f"数据库更新失败: {str(db_error)}", "data": None}), 500
        
        # 记录系统日志（可选，不影响主功能）
        try:
            ip_address = request.remote_addr
            operator = user.username if user else '未知用户'
            
            log_service.log_update(
                record=user,
                old_data=None,  # 个人中心不记录修改前数据
                operator=operator,
                ip_address=ip_address
            )
        except Exception as log_error:
            # 日志错误不影响主功能，只记录错误
            print(f"日志记录失败: {log_error}")
        
        return jsonify({"success": True, "message": "个人信息更新成功", "data": user.to_dict()}), 200
    except Exception as e:
        # 确保数据库事务回滚
        try:
            db.session.rollback()
        except:
            pass
        return jsonify({"success": False, "message": f"更新个人信息失败: {str(e)}", "data": None}), 500
